<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {
            background: #000;
            text-align: center
        }

        #c1 {
            background: #fff;
        }
    </style>

</head>

<body>
    <button id="btn1">变灰</button>
    <button id="btn2">变黄</button>
    <button id="btn3">保存</button>
    <canvas id="c1" width="800" height="600">

    </canvas>
    <img src="" alt="" id="img1">
</body>
<script>
    //*****不能跨域
    let oC = document.getElementById('c1');
    let gd = oC.getContext('2d');       //图形上下文-绘图用的接口
    let btn = document.getElementById('btn1');
    let btn2 = document.getElementById('btn2');
    let btn3 = document.getElementById('btn3');
    let img1=document.getElementById('img1');
    let img = new Image();
    img.src = '1.jpg';
    img.onload = function () {
        gd.drawImage(img, 0, 0)
        //获取像素区域
        btn.onclick = function () {
            let imageData = gd.getImageData(0, 0, oC.width, oC.height);
            //获取第1行第0列的像素值  r:行   c:列
            for (let r = 0; r < oC.height; r++) {
                for (let c = 0; c < oC.width; c++) {
                    //求平均值
                    let avg = (imageData.data[(r * oC.width + c) * 4] + imageData.data[(r * oC.width + c) * 4 + 1] + imageData.data[(r * oC.width + c) * 4 + 2]) / 3;
                    imageData.data[(r * oC.width + c) * 4] = imageData.data[(r * oC.width + c) * 4 + 1] = imageData.data[(r * oC.width + c) * 4 + 2] = avg

                }
            }
            gd.putImageData(imageData, 0, 0)
        }
        btn2.onclick = function () {
            let imageData = gd.getImageData(0, 0, oC.width, oC.height);
            //获取第1行第0列的像素值  r:行   c:列
            for (let r = 0; r < oC.height; r++) {
                for (let c = 0; c < oC.width; c++) {
                    imageData.data[(r * oC.width + c) * 4 + 2]=0
                }
            }
            gd.putImageData(imageData, 0, 0)
        }
        btn3.onclick=function(){
            //把图片转换成base64
            let str=oC.toDataURL;
            img1.src=str;
        }
    }


</script>
</html>